<template>
  <div class="consult-dep-page">
    <cp-nav-bar title="医生列表" />

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        shape="round"
        placeholder="搜索医生、疾病"
        @search="onSearch"
      />
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="currentDepartment"
          :options="departmentOptions"
          @change="onFilterChange"
        />
        <van-dropdown-item
          v-model="currentPrice"
          :options="priceOptions"
          @change="onFilterChange"
        />
        <van-dropdown-item
          v-model="currentSort"
          :options="sortOptions"
          @change="onFilterChange"
        />
      </van-dropdown-menu>
    </div>

    <!-- 医生列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :error="error"
        error-text="请求失败，点击重试"
        finished-text="没有更多了"
        @load="loadDoctorList"
      >
        <div class="doctor-list">
          <template v-if="!error">
            <div class="doctor-card" v-for="doctor in doctors" :key="doctor.id">
              <div class="doctor-info">
                <img :src="doctor.avatar" class="avatar" />
                <div class="info-right">
                  <div class="top-line">
                    <span class="name">{{ doctor.name }}</span>
                    <span class="title"
                      >{{ doctor.department }} | {{ doctor.title }}</span
                    >
                  </div>
                  <div class="hospital">{{ doctor.hospital }}</div>
                  <div class="expertise">{{ doctor.expertise }}</div>
                  <div class="bottom-line">
                    <div class="rating">
                      <van-icon name="star" class="star-icon" />
                      <span class="score">{{ doctor.rating }}</span>
                      <span class="consult-count"
                        >接诊数：{{ doctor.consultationCount }} | 完成：{{
                          doctor.finishedConsultCount
                        }}</span
                      >
                    </div>
                    <div class="price-action">
                      <span class="price">{{ doctor.price }}</span>
                      <van-button
                        class="consult-btn"
                        type="primary"
                        size="small"
                        round
                        @click="onConsult(doctor)"
                        >问医生</van-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <!-- 骨架屏 -->
          <template v-if="loading && !doctors.length">
            <div class="doctor-card" v-for="i in 3" :key="i">
              <van-skeleton title avatar :row="3" />
            </div>
          </template>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { Doctor } from '@/types/consult'
import { getDoctorList } from '@/services/consult'
import { showToast } from 'vant'
import { request } from '@/utils/request'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const error = ref(false)
const searchText = ref('')
const currentCity = ref('北京')
const cityOptions = ref([{ text: '北京', value: '北京' }])
const priceOptions = ref([
  { text: '不限价格', value: 'all' },
  { text: '0-100元', value: '0-100' },
  { text: '100-200元', value: '100-200' },
  { text: '200-300元', value: '200-300' },
  { text: '300元以上', value: '300-max' }
])
const currentPrice = ref('all')

const sortOptions = ref([
  { text: '综合排序', value: { sortBy: '', sortOrder: '' } },
  { text: '价格升序', value: { sortBy: 'price', sortOrder: 'asc' } },
  { text: '价格降序', value: { sortBy: 'price', sortOrder: 'desc' } }
])
const currentSort = ref({ sortBy: '', sortOrder: '' })

const departmentOptions = ref([{ text: '全部科室', value: '' }])

const loadDepartmentList = async () => {
  try {
    const res = await request.get('/consult/dep/all')
    const list = res.data

    // 确保值为字符串类型，保持一致性
    departmentOptions.value = list.map((item) => ({
      text: item.name,
      value: item.id.toString() // 转换为字符串
    }))
    departmentOptions.value.unshift({ text: '全部科室', value: '' })

    // 在科室列表加载完成后，再设置当前选中的科室
    if (route.query.departmentId) {
      const departmentId = route.query.departmentId as string
      console.log('URL参数 departmentId:', departmentId)
      console.log('科室选项列表:', departmentOptions.value)

      // 检查该科室是否存在于选项中
      const exists = departmentOptions.value.some(
        (option) => option.value === departmentId
      )
      console.log('科室是否存在:', exists)

      if (exists) {
        currentDepartment.value = departmentId
        console.log('设置科室选中:', departmentId)
      } else {
        // 如果科室不存在，默认选择全部科室
        currentDepartment.value = ''
        console.log('科室不存在，选择全部科室')
      }
    }
  } catch (error) {
    console.error('加载科室列表失败:', error)
    // 如果加载失败，确保有默认选项
    departmentOptions.value = [{ text: '全部科室', value: '' }]
  }
}

// 初始化页面参数
const initializeParams = () => {
  // 如果URL中有keyword参数，则自动填入搜索框
  if (route.query.keyword) {
    searchText.value = route.query.keyword as string
  }
}

onMounted(() => {
  initializeParams()
  loadDepartmentList()
  loadDoctorList()
})

const currentDepartment = ref('')

// 分页数据
const pageSize = 10
const pageNum = ref(1)
const doctors = ref<Doctor[]>([])

// 获取医生列表
const loadDoctorList = async (isRefresh = false) => {
  // 如果是刷新，重置状态
  if (isRefresh) {
    pageNum.value = 1
    doctors.value = []
    error.value = false
    finished.value = false
  }

  try {
    loading.value = true
    //根据部门id查询
    console.log('currentDepartment.value', currentDepartment.value)

    // 处理价格范围
    let minPrice, maxPrice
    if (currentPrice.value !== 'all') {
      const [min, max] = currentPrice.value.split('-')
      minPrice = Number(min)
      maxPrice = max === 'max' ? undefined : Number(max)
    }

    const res = await getDoctorList({
      pageSize,
      pageNum: pageNum.value,
      keyword: searchText.value,
      departmentId: currentDepartment.value
        ? parseInt(currentDepartment.value)
        : undefined,
      minPrice,
      maxPrice,
      sortBy: currentSort.value.sortBy,
      sortOrder: currentSort.value.sortOrder
    })

    console.log('医生列表API请求参数:', {
      pageSize,
      pageNum: pageNum.value,
      keyword: searchText.value,
      departmentId: currentDepartment.value
        ? parseInt(currentDepartment.value)
        : undefined,
      minPrice,
      maxPrice,
      sortBy: currentSort.value.sortBy,
      sortOrder: currentSort.value.sortOrder
    })
    console.log('医生列表API响应:', res)

    // 处理不同的响应格式
    let doctorData: any[] = []
    if (res.data) {
      // 检查是否是统一的Result格式 {success: true, data: [...]}
      if (res.data.success && res.data.data) {
        doctorData = res.data.data
      }
      // 检查是否直接是数组数据
      else if (Array.isArray(res.data)) {
        doctorData = res.data
      }
    }

    if (doctorData && doctorData.length) {
      // 转换数据结构以适配现有的展示逻辑
      const formattedDoctors = doctorData.map((doctor: any) => ({
        id: doctor.id,
        name: doctor.doctorName,
        avatar: doctor.imgUrl, // 使用imgUrl而不是avatar
        department: doctor.departments || '暂无科室',
        title: doctor.socialPosition || '暂无职称',
        hospital: '三甲 北京协和医院',
        expertise: `擅长：${doctor.expertise || '暂无擅长信息'}`,
        rating: doctor.avgScore || 5,
        consultationCount: doctor.consultCount,
        finishedConsultCount: doctor.finishedConsultCount,
        price: doctor.price
      }))

      doctors.value.push(...formattedDoctors)
      pageNum.value++

      // 如果返回的数据少于pageSize，说明没有更多数据了
      if (doctorData.length < pageSize) {
        finished.value = true
      }
    } else {
      finished.value = true
      // 只有当明确返回失败时才抛出错误
      if (res.data && res.data.success === false) {
        throw new Error('获取医生列表失败')
      }
    }
    error.value = false
  } catch (e) {
    error.value = true
    showToast('获取医生列表失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  loadDoctorList(true)
}

// 搜索
const onSearch = () => {
  loadDoctorList(true)
}

// 筛选条件变化
const onFilterChange = () => {
  // 使用 nextTick 来避免递归更新
  nextTick(() => {
    loadDoctorList(true)
  })
}

// 问诊
const onConsult = (doctor: Doctor) => {
  router.push(`/doctor/${doctor.id}`)
}
</script>

<style lang="scss" scoped>
.consult-dep-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background: #fff;
  padding: 10px 15px;
  .van-search {
    padding: 0;
    background: transparent;
  }
}

.filter-bar {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.doctor-list {
  padding: 10px 15px;
  .doctor-card {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 10px;

    .doctor-info {
      display: flex;
      .avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
        flex-shrink: 0;
      }

      .info-right {
        flex: 1;
        min-width: 0;
        .top-line {
          display: flex;
          align-items: center;
          margin-bottom: 5px;
          flex-wrap: nowrap;
          .name {
            font-size: 16px;
            font-weight: bold;
            margin-right: 8px;
            color: #121826;
            white-space: nowrap;
            flex-shrink: 0;
            max-width: 80px;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .title {
            color: #6f6f6f;
            font-size: 13px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
            min-width: 0;
          }
        }

        .hospital {
          color: #6f6f6f;
          font-size: 13px;
          margin-bottom: 5px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .expertise {
          color: #999;
          font-size: 12px;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          line-height: 16px;
          height: 32px;
        }

        .bottom-line {
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex-wrap: nowrap;

          .rating {
            display: flex;
            align-items: center;
            flex: 1;
            min-width: 0;
            margin-right: 8px;

            .star-icon {
              color: #ffcc00;
              font-size: 12px;
              flex-shrink: 0;
            }

            .score {
              color: #ff9500;
              font-size: 12px;
              margin: 0 4px;
              flex-shrink: 0;
            }

            .consult-count {
              color: #6f6f6f;
              font-size: 12px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              min-width: 0;
            }
          }

          .price-action {
            display: flex;
            align-items: center;
            flex-shrink: 0;
            .price {
              color: #ff5f5f;
              font-size: 16px;
              margin-right: 8px;
              white-space: nowrap;
              &::before {
                content: '¥';
                font-size: 14px;
              }
            }
            .consult-btn {
              background-color: #16c2a3;
              border: none;
              padding: 0 12px;
              height: 24px;
              line-height: 24px;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
}
</style>
